package com.ta.gulimall.cart.component.handler;

import com.ta.gulimall.common.constant.AuthConstant;
import com.ta.gulimall.common.view.vo.MemberVo;
import com.ta.gulimall.cart.view.to.UserInfoTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Optional;
import java.util.UUID;

public class TempWithUserHandler implements HandlerInterceptor {

    public static final ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberVo loginUser = (MemberVo) session.getAttribute(AuthConstant.LOGIN_USER);

        UserInfoTo userInfoTo = new UserInfoTo();
        if (loginUser != null) {
            userInfoTo.setUserId(loginUser.getId());
        }

        Cookie cookie = Arrays.stream(Optional.ofNullable(request.getCookies()).orElse(new Cookie[0]))
                .filter(f -> f.getName().equals(AuthConstant.TEMP_USER)).findFirst().orElse(null);


        if (cookie != null) {
            userInfoTo.setUserKey(cookie.getValue());
        }else{
            UUID uuid = UUID.randomUUID();
            userInfoTo.setUserKey(uuid.toString());
            userInfoTo.setTempUser(Boolean.TRUE);
        }

        threadLocal.set(userInfoTo);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(AuthConstant.TEMP_USER, userInfoTo.getUserKey());
            cookie.setMaxAge(AuthConstant.TEMP_USER_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
